﻿using IntelligentGateway.Model;
using IntelligentGateway.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace CompassPlus360.Controllers.api
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginApiController : ControllerBase
    {

        private JwtSettings _jwtSettings;
        
        JwtToken _jwttoken = new JwtToken();
        


        public LoginApiController(IOptions<JwtSettings> jwtSettingsAccesser,
            IHttpContextAccessor access
            )
        {
            _jwtSettings = jwtSettingsAccesser.Value;            
        }

        [HttpPost]
        [Route("LoginProc")]
        public ResponseMessage LoginProc(string UserName, string Password)
        {            
            ResponseMessage result = new ResponseMessage();
            LoginServices services = new LoginServices();          
            
            UserInfo? user = services.LoginProcess(UserName, Password);
            if (user != null)
            {
                string token = services.MakeToken(user,_jwtSettings);
                if (token.Equals(""))
                {
                    result.errcode = 1; result.errmsg = "生成Token错误"; result.data = null;
                    return result;
                }
                _jwttoken.Token = token;
                user.Token = _jwttoken.Token;
                result.errcode = 0; result.errmsg = ""; result.data = user;

            }
            else
            {
                result.errcode = 1; result.errmsg = "登录失败!"; result.data = null;
            }
            return result;
        }
        [HttpPost]
        [Route("RefreshToken")]
        public ResponseMessage RefreshToken(string Token)
        {
            LoginServices services = new LoginServices();
            try
            {
                var principal = services.GetPrincipalFromExpiredToken(Token,_jwtSettings);
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new JwtSecurityToken
                (
                    issuer: _jwtSettings.Issuer,
                    audience: _jwtSettings.Audience,
                    claims: principal.Claims,
                    notBefore: DateTime.Now,
                    expires: DateTime.Now.AddHours(2),//过期时间                
                    signingCredentials: creds
                );
                string strToken = new JwtSecurityTokenHandler().WriteToken(token);
                return new ResponseMessage() { data = strToken, errcode = 0, errmsg = "" };
            }
            catch (Exception ee)
            {
                return new ResponseMessage() { data = "", errcode = 1, errmsg = ee.ToString() };
            }
        }
    }
}
